<?php
namespace passport;

use app\home\model\AccessToken;
use app\home\model\Openid;
use nekoing\AppException;
use nekoing\ErrorCode;
use app\home\model\User;

/**
 *
 * @author Nekoing
 */
class AccessTokenHelper
{

    /**
     *
     * @return \app\home\model\AccessToken
     */
    public static function getAccessToken()
    {
        static $accessToken;
        if (! $accessToken) {
            $accessToken = AccessToken::check(input('access_token'));
        }
        return $accessToken;
    }

    /**
     * @throws AppException
     * @return \app\home\model\User
     */
    public static function getUser()
    {
        static $user;
        if (! $user) {
            $accessToken = self::getAccessToken();
            $openid = Openid::get([
                'openid' => $accessToken->openid
            ]);
            
            if (! $openid) {
                throw new AppException(ErrorCode::DATA_NOT_EXISTS, 'openid不存在');
            }
            
            if ($openid->appid != $accessToken->appid) {
                throw new AppException(ErrorCode::OPENID_NOT_MATCH);
            }
            
            $user = User::get($openid->uid);
            if (! $user) {
                throw new AppException(ErrorCode::DATA_NOT_EXISTS, '用户不存在');
            }
        }
        
        return $user;
    }

    public static function checkAccess($openid, $scope)
    {
        $token = self::getAccessToken();
        AccessToken::check($token, $openid, $scope);
    }
}